<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace common\models;

use Yii;
use yii\helpers\ArrayHelper;

class SystemAuthRelationService
{
    /**
     * 获取权限树数据
     * @param int $group 管理组
     * @param int $parentGroup 父管理组
     * @return array
     */
    public static function permissionTree($group, $parentGroup)
    {
        $auth = Yii::$app->rbacManager;
        $permission = $auth->getPermissionsFromDb($group);
        $myPermissions = ArrayHelper::getColumn($permission, 'id', false);
        $canDispatch = $auth->getPermissionsFromDb($parentGroup);

        return self::getPermissionRecursive($canDispatch, $myPermissions);
    }

    /**
     * 递归标记已拥有的权限
     * @param array $canDispatch 可以分配的权限
     * @param array $myPermissions 已拥有权限
     * @param int $pid 父ID
     * @return array
     */
    protected static function getPermissionRecursive($canDispatch, $myPermissions, $pid = 0)
    {
        $result = [];
        foreach ($canDispatch as $i => $item) {
            if ($item['pid'] == $pid) {
                unset($canDispatch[$i]);

                $item['children'] = self::getPermissionRecursive($canDispatch, $myPermissions, $item['id']);
                if (in_array($item['id'], $myPermissions) && empty($item['children'])) {
                    $item['checked'] = true;
                }

                $result[] = $item;
            }
        }

        return $result;
    }
}